<template>
  <div class="scene_box">
    <p>创建纹理贴图TextureLoader</p>
    <div class="canvas"></div>
  </div>
</template>
      
 <script setup>
import { nextTick } from "vue";
import img from "../../js/chapter5/cizhuan.jpg";
import * as THREE from "three";
// 引入threejs 的扩展库  相机轨道控件
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

nextTick(() => {
  // ******************创建一个场景*************
  const geometry = new THREE.PlaneGeometry(2000, 2000); //正方形平面

  //纹理贴图加载器TextureLoader
  const texLoader = new THREE.TextureLoader();
  // .load()方法加载图像，返回一个纹理对象Texture
  const texture = texLoader.load(img);
  // 设置阵列模式
  texture.wrapS = THREE.RepeatWrapping;
  texture.wrapT = THREE.RepeatWrapping;
  // .repeat设置UV方向阵列多少个
  texture.repeat.set(10, 10);
  const material = new THREE.MeshLambertMaterial({
    // color: 0x00ffff,
    // 设置纹理贴图：Texture对象作为材质map属性的属性值
    map: texture, //map表示材质的颜色贴图属性
  });

  // material.map = texture;//也可以通过map属性直接设置，材质的参数设置一样

  const mesh = new THREE.Mesh(geometry, material);
  //场景
  const scene = new THREE.Scene();
  mesh.rotateX(-Math.PI/2)
  scene.add(mesh); //模型对象添加到场景中

  //辅助观察的坐标系
  const axesHelper = new THREE.AxesHelper(150);
  scene.add(axesHelper);

  //光源设置
  const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  directionalLight.position.set(1000, 1000, 1000);
  scene.add(directionalLight);
  const ambient = new THREE.AmbientLight(0xffffff, 0.4);
  scene.add(ambient);

  //渲染器和相机
  let dom = document.querySelector(".canvas");
  const width = dom.offsetWidth;
  const height = dom.offsetHeight;
  const camera = new THREE.PerspectiveCamera(50, width / height, 1, 10000);
  camera.position.set(1000, 1500, 1300);
  camera.lookAt(0, 0, 0);

  const renderer = new THREE.WebGLRenderer({
    antialias: true, //去除锯齿
  });
  renderer.setSize(width, height);
  dom.appendChild(renderer.domElement);

  // 渲染循环
  function render() {
    // scene.rotateY(0.005);
    renderer.render(scene, camera);
    requestAnimationFrame(render);
    console.log(camera.position, "相机定位");
  }
  render();

  const controls = new OrbitControls(camera, renderer.domElement);

  // 画布跟随窗口变化
  window.onresize = function () {
    renderer.setSize(dom.offsetWidth, dom.offsetHeight);
    camera.aspect = dom.offsetWidth / dom.offsetHeight;
    camera.updateProjectionMatrix();
  };
  renderer.setPixelRatio(window.devicePixelRatio);
});
</script>
      
      
<style  scoped>
.canvas {
  width: 80vw;
  height: 60vh;
}
</style>